#include "stdio.h"
#include "stdlib.h"
#include "unistd.h"
#include "util.c"
#include "wonCheck.c"
#include "bot.c"
// ═ ║ ╔ ╚ ╗ ╝ ╠ ╣ ╩ ╦ ╬

int main(){
	system("clear");

	int score[3] = {0, 0, 0}; // 0 - X, 1 - 0
	char field[3][3] = {
		{'*', '*', '*'},
		{'*', '*', '*'},
		{'*', '*', '*'}
	};
	bool whoIswho = true; // X - true, 0 - false
	int winner = 0; //-1 : 0 : 1 - X, NONE, 0
	int counter = 0;

	while(true){ //global loop
		char who = whoIswho == true ? 'X' : '0'; //who move now
		char enemy = whoIswho == true ? '0' : 'X'; //who enemy now
		int pos = 0;
		//io:
		print_board(winner, score);

		print_field(field);


		if(whoIswho){
				printf("Ход [%c]: ", who);
				scanf("%d", &pos);
			}
		else {
			//printf("Погоди, дай подумать...\n");
			pos = make_turn(field, who, enemy);
		}
		
		if ((pos % 10 > 0 || pos % 10 <= 3) && (pos / 10 > 0 || pos / 10 <= 3) && field[(pos / 10)-1][(pos % 10)-1] == '*'){
			whoIswho = !whoIswho;
			field[(pos / 10)-1][(pos % 10)-1] = who;

			counter++;

			if (counter == 9) {

				score[2]++;

				system("clear");

				print_board(winner, score);

				print_field(field);

				printf("Ничья!\n");

				sleep(3);

				system("clear");


				for (int i = 0; i < 3; i++){
					for (int j = 0; j < 3; j++){
						field[i][j] = '*';
						winner = 0;
						counter = 0;
					}
				}
			}
		}
		bool is_Won = isWon(field);

		if (is_Won){
			score[whoIswho]++;
			counter = 0;
			winner = (!whoIswho == true ? -1 : 1);

			system("clear");

			print_board(winner, score);

			print_field(field);

			printf("[%c] победил!\n", who);

			sleep(3);

			for (int i = 0; i < 3; i++){
				for (int j = 0; j < 3; j++){
					field[i][j] = '*';
					whoIswho = !whoIswho;
					counter = 0;
				}
			}
		}
		system("clear");
		//printf("+----+\ndebug info \nprevious turn: \npos: %d\nis won: %d\nwho: %c\ncounter: %d\nwinner: %d\n+----+\n", pos, is_Won, who, counter, winner); //debug info
	}
	return 0;
}
